<template>
  <div class="tradein-order-page">
    <n-grid :cols="24">
      <n-grid-item span="24">
        <detail-page-header title="回收订单详情">
          <n-space>
            <n-button
              type="primary"
              v-if="canAddPayment"
              class="flex items-center"
              @click.stop="handleClickkAddPayment"
            >
              <span>支付</span>
            </n-button>
            <n-button
              v-if="canCancel"
              @click.stop="handleCancelOrder"
              type="error"
            >
              取消订单
            </n-button>
            <n-popconfirm
              v-if="canComplete"
              @positive-click="handleChangeOrderStatus"
            >
              <template #trigger>
                <n-button type="success">完成订单</n-button>
              </template>
              您确定要完成当前订单吗？
            </n-popconfirm>
            <n-button
              v-if="purchaseInfo.status === 'complete'"
              @click.stop="handlePrint"
            >
              打印凭证
            </n-button>
          </n-space>
        </detail-page-header>
        <div class="mt-[16px]"></div>
        <n-grid :col="24" x-gap="10">
          <n-grid-item span="14">
            <n-card>
              <div class="flex justify-between">
                <n-h3>
                  <span class="mr-2">{{ purchaseInfo.num }}</span>
                </n-h3>
                <DictTag
                  v-if="purchaseInfo.status"
                  dict="pos_purchase_status"
                  :value="purchaseInfo.status"
                />
              </div>
              <div class="flex items-center">
                <n-icon>
                  <TimeOutline />
                </n-icon>
                <span class="ml-1"
                  >创建时间：{{ purchaseInfo.createTime }}</span
                >
              </div>
              <div class="mt-[16px]"></div>
              <n-card size="small">
                <div class="mb-2">
                  <span class="font-bold text-base">回收设备清单</span>
                </div>
                <!-- ITEMS -->
                <div
                  class="purchase-item"
                  v-for="item in purchaseItems"
                  :key="item.id"
                >
                  <div class="flex">
                    <div class="flex-1 flex justify-between mr-10">
                      <span>{{ item.variantName }}</span>
                      <span>{{ item.quantity }}</span>
                    </div>
                    <div class="text-right">
                      <span>{{ currencyFormat(item.rowTotal) }}</span>
                    </div>
                  </div>
                  <div
                    class="flex justify-between items-center mt-1"
                    v-for="sn in item.snName"
                    :key="sn"
                  >
                    <div>
                      <span>序列号/IMEI：</span>
                      <span>{{ sn }}</span>
                    </div>
                    <n-button
                      type="success"
                      secondary
                      size="small"
                      @click.stop="
                        handleShowCheckResult(item.id, item.variantName)
                      "
                    >
                      <template #icon>
                        <n-icon>
                          <List />
                        </n-icon>
                      </template>
                    </n-button>
                  </div>
                </div>

                <template #action>
                  <div class="flex justify-between">
                    <span class="font-bold text-base">订单总金额：</span>
                    <span class="font-bold text-base">
                      {{ currencyFormat(purchaseInfo.total) }}
                    </span>
                  </div>
                </template>
              </n-card>
              <!-- NOTES -->
              <div class="mt-[16px]">
                <div class="mb-2">
                  <span class="font-bold text-base">备注：</span>
                </div>
                <n-spin :show="getPurchaseNotesLoading">
                  <template v-if="purchaseNotesList.length">
                    <div
                      class="note-item"
                      v-for="note in purchaseNotesList"
                      :key="note.id"
                    >
                      <div class="content">
                        <span>{{ note.message }}</span>
                      </div>
                      <div class="create-time">
                        <span>{{ note.createTime }}</span>
                      </div>
                    </div>
                  </template>
                  <n-empty v-else> </n-empty>
                </n-spin>
                <div class="mt-2">
                  <n-input
                    v-model:value="createPurchaseNoteForm.note"
                    type="textarea"
                    placeholder="请输入备注信息"
                  />
                </div>
                <div class="mt-2 text-right">
                  <n-button
                    :disabled="!createPurchaseNoteForm.note"
                    @click.stop="handleAddNote"
                    :loading="getPurchaseNotesLoading"
                    >保存备注</n-button
                  >
                </div>
              </div>
            </n-card>
          </n-grid-item>
          <n-grid-item span="10">
            <n-card>
              <n-h3>客户信息</n-h3>
              <div class="mt-[16px]">
                <n-grid :cols="24" :x-gap="10" :y-gap="10">
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon> <Person /> </n-icon
                      ><span class="ml-1">姓名</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ customerInfo.name }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon> <PhonePortraitOutline /> </n-icon
                      ><span class="ml-1">联系电话</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ customerInfo.phoneNumber }}</span>
                    </div>
                  </n-grid-item>
                  <n-grid-item span="12">
                    <div class="flex items-center text-sm text-gray-500">
                      <n-icon> <Mail /> </n-icon><span class="ml-1">邮箱</span>
                    </div>
                    <div class="text-base mt-1">
                      <span>{{ customerInfo.email || "/" }}</span>
                    </div>
                  </n-grid-item>
                </n-grid>
              </div>
            </n-card>
            <div class="mt-[10px]"></div>
            <n-card>
              <n-h3>支付信息</n-h3>
              <div class="mb-2 flex justify-between items-center">
                <span class="font-bold text-base">已支付金额：</span>
                <span class="font-bold">
                  {{ currencyFormat(purchaseInfo.paidAmount) }}
                </span>
              </div>
              <!-- PAYMENT ITEM -->
              <div
                class="payment-item"
                v-for="item in paymentsList"
                :key="item.id"
              >
                <div>
                  <div class="desc">
                    <span>支付订单编号：</span>
                    <span class="payment-num">#{{ item.id }}</span>
                  </div>
                  <div class="amount">
                    <span>
                      {{ getPaymentMethodName(item.method) }} -
                      {{ currencyFormat(item.amount) }}
                    </span>
                  </div>
                  <div class="desc mt-1">
                    <span>{{ item.createTime }}</span>
                  </div>
                </div>
                <div>
                  <img
                    class="w-[48px]"
                    :src="getPaymentAsset(`${item.method}.png`)"
                  />
                </div>
              </div>
            </n-card>
          </n-grid-item>
        </n-grid>
      </n-grid-item>
    </n-grid>
    <!-- 问题清单弹窗 -->
    <CheckResultModal
      :title="checkResultTitle"
      :checkResultList="checkResultList"
      v-model:show="showCheckResult"
      @close="showCheckResult = false"
      :show-footer="false"
    >
      <template v-slot:name="{ checkResult }">
        {{ checkResult.questionName }}
      </template>
    </CheckResultModal>
    <!-- 添加支付方式弹窗 -->
    <PaymentModal
      title="选择支付方式"
      payment-title="待支付金额"
      :payment-methods="paymentMethods"
      :total-price="dueAmount"
      :confirm-loading="paymentConfirmLoading"
      :check-equels="false"
      v-model:show="showPayment"
      @cancel="handleHidePayment"
      @close="handleHidePayment"
      @confirm="handleConfirmAddPayment"
    />
    <!-- 打印 -->
    <!-- <TradeInReceiptA4 ref="receiptContent" :order-id="id" /> -->
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { debounce, get } from "lodash-es";
import Big from "big.js";
import { useMessage } from "naive-ui";
import {
  TimeOutline,
  List,
  Person,
  PhonePortraitOutline,
  Mail,
} from "@vicons/ionicons5";
import { addTradeInPayment } from "@/api/purchase/purchase.api";
import {
  getPurchaseOrderDetail,
  completeOrder,
  cancelOrder,
} from "@/api/tradein/tradein.api";

import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { TradeInOrderDetailVO } from "@/types/model/tradein/vos/tradein.vo";
import { DictStorage } from "@/storage/dict.storage";
import {
  useCheckResultModal,
  CheckResultModal,
} from "@/components/biz/checkResultModal/index.ts";
import {
  usePaymentModal,
  PaymentModal,
} from "@/components/biz/paymentModal/index.ts";
import {
  getPaymentAsset,
  getPaymentMethodName,
} from "@/common/utils/payment/index";
import DictTag from "@/components/biz/dictTag/index.vue";
import { ITradeInOrderDetailProps } from "./props";
import { useNote } from "./hooks/useNote.ts";
import { router } from "@/router/index.ts";
import { TRADEIN_RECEIPT_PAGE } from "@/router/routerNames/index";

const props = defineProps<ITradeInOrderDetailProps>();

const paymentMethods = DictStorage.getDictItemsByCode(
  "pos_tradein_payment_method"
);

const confirmLoading = ref<boolean>(false);

const message = useMessage();

const {
  showCheckResult,
  checkResultList,
  checkResultTitle,
  handleGetCheckResult,
} = useCheckResultModal();

const {
  modalShowFlag: showPayment,
  handleShowModal: handleShowPaymentModal,
  handleHideModal: handleHidePaymentModal,
} = usePaymentModal();

const {
  createPurchaseNoteForm,
  getPurchaseNotesLoading,
  purchaseNotesList,
  handleAddTradeInNote,
  handleGetPurchaseNotes,
} = useNote();

const paymentConfirmLoading = ref<boolean>(false);

const orderDetail = ref<TradeInOrderDetailVO>({} as TradeInOrderDetailVO);

const canComplete = computed<boolean>(() => {
  const status = get(orderDetail.value, "posPurchase.status");
  return status === "paid";
});

const canCancel = computed<boolean>(() => {
  const status = get(orderDetail.value, "posPurchase.status");
  return status !== "complete" && status !== "cancelled";
});

const canAddPayment = computed<boolean>(() => {
  const status = get(orderDetail.value, "posPurchase.status");
  return status === "unpaid";
});

const dueAmount = computed(() => {
  const total = get(orderDetail.value, "posPurchase.total") || 0;
  const paidAmount = get(orderDetail.value, "posPurchase.paidAmount") || 0;
  return new Big(total).minus(paidAmount).toNumber();
});

const purchaseInfo = computed(() => {
  return get(orderDetail.value, "posPurchase") || {};
});

const purchaseItems = computed(() => {
  return get(orderDetail.value, "items") || [];
});

const customerInfo = computed(() => {
  return get(orderDetail.value, "customer") || {};
});

const paymentsList = computed(() => {
  return get(orderDetail.value, "payments") || [];
});

const handleGetOrderDetail = async (orderId: string) => {
  const result = await getPurchaseOrderDetail(orderId);
  orderDetail.value = result.result;
};

const handleShowCheckResult = handleGetCheckResult;

const handleHidePayment = () => {
  if (!paymentConfirmLoading.value) {
    handleHidePaymentModal();
  }
};

const handleConfirmAddPayment = debounce(async function (
  paymentMethods: any[]
) {
  const purchaseId = get(orderDetail.value, "posPurchase.id") || "";
  if (!purchaseId) {
    return;
  }
  const params = {
    purchaseId,
    paymentItems: paymentMethods.map((item) => {
      return {
        method: item.paymentMethod,
        amount: item.amount,
      };
    }),
  };
  const result = await addTradeInPayment(params);
  console.log(result);
});

const handleClickkAddPayment = () => {
  handleShowPaymentModal();
};

const handleAddNote = debounce(function () {
  handleAddTradeInNote(props.id);
}, 200);

const handleChangeOrderStatus = async () => {
  confirmLoading.value = true;
  try {
    await completeOrder(props.id);
    message.success("当前订单已完成");
    init();
  } finally {
    confirmLoading.value = false;
  }
};

const handleCancelOrder = async () => {
  confirmLoading.value = true;
  try {
    await cancelOrder(props.id);
    message.success("订单取消成功");
    init();
  } finally {
    confirmLoading.value = false;
  }
};

const handlePrint = () => {
  const routeData = router.resolve({
    name: TRADEIN_RECEIPT_PAGE.NAME,
    params: {
      orderId: props.id,
    },
  });

  // 在新标签页中打开
  window.open(routeData.href, "_blank");
};

const init = () => {
  handleGetOrderDetail(props.id);
  handleGetPurchaseNotes(props.id);
};

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
